package com.pxmeta.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.enums.ContentAuditEnum;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.user.entity.StudentAuth;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.entity.UserPhoto;
import com.pxmeta.user.entity.dto.PhotoDTO;
import com.pxmeta.user.mapper.StudentAuthMapper;
import com.pxmeta.user.mapper.UserPhotoMapper;
import com.pxmeta.user.service.IStudentAuthService;
import com.pxmeta.user.service.IUserPhotoService;
import com.pxmeta.user.service.IUserService;
import com.pxmeta.verify.service.VerifyService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 学生认证Service业务层处理
 *
 * @author wcl
 * @date 2022-03-21
 */
@Service
@RequiredArgsConstructor
public class UserPhotoServiceImpl extends ServiceImpl<UserPhotoMapper, UserPhoto> implements IUserPhotoService {

    private final VerifyService verifyService;
    private final IUserService userService;

    @Override
    @SneakyThrows
    @Transactional(rollbackFor = ServiceException.class)
    public void saveUserPhotos(Long userId, List<PhotoDTO> images) {
//        String status = verifyService.auditImg(images.stream().map(PhotoDTO::getImgUrl).collect(Collectors.toList()));
//        if (ContentAuditEnum.BLOCK.getSuggestion().equals(status)){
//            throw new ServiceException("上传的图片有违规，请重新上传！");
//        }

        LambdaQueryWrapper<UserPhoto> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserPhoto::getUserId, userId);
        this.remove(wrapper);
        if (images.size() > 9){
            throw new ServiceException("上传数量超过限制！");
        }

        List<UserPhoto> userPhotos = Lists.newLinkedList();
        for (PhotoDTO image : images) {
            UserPhoto userPhoto = new UserPhoto();
            userPhoto.setUserId(userId);
            userPhoto.setPhotoUrl(image.getImgUrl());
            userPhoto.setStatus(Status.SUCCESS.getValue());
            userPhoto.setSort(image.getOrder());
            userPhotos.add(userPhoto);
        }
        this.saveBatch(userPhotos);
        User user = new User();
        user.setId(userId);
        user.setIsOpenPhoto(true);
        userService.updateById(user);
    }
}
